package io.renren.modules.app.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.renren.common.exception.RRException;
import io.renren.common.utils.R;
import io.renren.modules.PCguanli.entity.LineDeptEntity;
import io.renren.modules.app.dao.LinedptDao;
import io.renren.modules.app.dao.UserDao;
import io.renren.modules.app.dao.UserRegistrationDao;
import io.renren.modules.app.dao.UserWithCarNumberDao;
import io.renren.modules.app.entity.*;
import io.renren.modules.app.service.RegistratiService;
import io.renren.modules.app.service.UserService;
import io.renren.modules.app.service.UserWithCarNumberService;
import io.renren.modules.app.user.UserPicUpdateVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: UserInfoController
 * Package: io.renren.modules.app.controller
 * Description:
 *
 * @Author zzy
 * @Create 2024/3/25 21:01
 * @Version 1.0
 */
@RestController
@RequestMapping("/app/user")
@Slf4j
public class UserInfoController {
    @Autowired
    private RegistratiService registratiService;
    @Autowired
    private UserRegistrationDao userRegistrationDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private LinedptDao linedptDao;
    @Autowired
    private UserWithCarNumberDao userWithCarNumberDao;
    @GetMapping("/info") //返回司机用户信息
    public Response user(@RequestParam int userId) {
        UserEntity user = userService.queryByuserID(userId);
        if (user == null) {
            return new Response(404, "用户不存在", null);
        }
        UserWithCarNumber userWithCarNumber = new UserWithCarNumber(user, user.getCarnumber());
        return new Response(0, "success", userWithCarNumber);
    }

/*    @GetMapping("/resiinfo") //返回报到资料
    public Response resident(@RequestParam int recordId) {
        UserRegistrationEntity userRegistrationEntity = userRegistrationDao.selectOne(new LambdaQueryWrapper<UserRegistrationEntity>()
                .eq(UserRegistrationEntity::getRecordid,recordId));
        if (userRegistrationEntity == null) {
            return new Response(404, "用户还未车检", null);
        }
        return new Response(0, "success", userRegistrationEntity);
    }*/
    @GetMapping("/resiinfo") //返回报到资料
    public Response resident(@RequestParam int recordId) {
        Map<String, Object> map = new HashMap<>();
        UserRegistrationEntity userRegistrationEntity = userRegistrationDao.selectOne(new LambdaQueryWrapper<UserRegistrationEntity>()
                .eq(UserRegistrationEntity::getRecordid,recordId));
        if (userRegistrationEntity == null) {
            throw new RuntimeException("用户未车检");
        }
        map.put("recordid",userRegistrationEntity.getRecordid());
        map.put("driverid",userRegistrationEntity.getDriverid());
        map.put("datcherid",userRegistrationEntity.getDatcherid());
        map.put("reid",userRegistrationEntity.getReid());
        map.put("carnumber",userRegistrationEntity.getCarnumber());
        map.put("time",userRegistrationEntity.getTime());
        map.put("state",userRegistrationEntity.getState());
        map.put("way",userRegistrationEntity.getWay());
        map.put("carrythings",userRegistrationEntity.getCarrythings());
        map.put("tonnage",userRegistrationEntity.getTonnage());
        map.put("purchaseplant",userRegistrationEntity.getPurchaseplant());
        map.put("emissionstandard",userRegistrationEntity.getEmissionstandard());
        map.put("carshop",userRegistrationEntity.getCarshop());
        map.put("picture",userRegistrationEntity.getPicture());
        map.put("model",userRegistrationEntity.getModel());
        map.put("orderNumber",userRegistrationEntity.getOrderNumber());
        if(userRegistrationEntity.getDatcherid() ==null){
            map.put("datchername",null);
            map.put("datcheriphone",null);
            return new Response(0, "success", map);
        }
        UserEntity user = userService.queryByuserID(userRegistrationEntity.getDatcherid());
        map.put("datchername",user.getName());
        map.put("datcheriphone",user.getIPhone());
        return new Response(0, "success", map);
    }
    @GetMapping("/resIDinfo") //通过身份证deptid,报到时间查询报到资料
    public Response resident(@RequestParam String ID,@RequestParam String deptid,@RequestParam String time) {
        UserEntity userEntity = userDao.findByID(ID);
        LineDepEntity lineDepEntity = linedptDao.selectOne(new LambdaQueryWrapper<LineDepEntity>().eq(LineDepEntity::getDeptId,deptid));
        UserRegistrationEntity userRegistrationEntity1 = userRegistrationDao.selectOne(new LambdaQueryWrapper<UserRegistrationEntity>()
                .eq(UserRegistrationEntity::getDriverid,userEntity.getUser_id())
                .eq(UserRegistrationEntity::getPurchaseplant,lineDepEntity.getDeptName())
                .eq(UserRegistrationEntity::getTime, time));
        if (userRegistrationEntity1 == null) {
            return new Response(404, "用户不存在", null);
        }
        return new Response(0, "success", userRegistrationEntity1);
    }

    @PostMapping("/updateregistraition")  // 填写报到资料
    public Response updateregistraition(@RequestParam int userId,
                                        @RequestParam String way,
                                        @RequestParam String carrythings,
                                        @RequestParam String tonnage,
                                        @RequestParam String carshop,
                                        @RequestParam @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") String time,
                                        @RequestParam int recordId,
                                        @RequestParam String name,
                                        @RequestParam String iphone) {
        try {
            UserRegistrationEntity updaInfo = registratiService.updateresInfo( userId,   way, carrythings,  tonnage,carshop,time,recordId,name,iphone);
            Map<String, Object> map = new HashMap<>();

            if(updaInfo.getDatcherid()==null){
                map.put("datcheriphone",null);
                map.put("datchername",null);
            }
            else{
                UserEntity user = userService.queryByuserID(updaInfo.getDatcherid());
                map.put("datcheriphone",user.getIPhone());
                map.put("datchername",user.getName());
            }
            map.put("driverid",updaInfo.getDriverid());
            map.put("datcherid",updaInfo.getDatcherid());
            map.put("reid",updaInfo.getReid());
            map.put("carnumber",updaInfo.getCarnumber());
            map.put("time",updaInfo.getTime());
            map.put("state",updaInfo.getState());
            map.put("way",updaInfo.getWay());
            map.put("carrythings",updaInfo.getCarrythings());
            map.put("tonnage",updaInfo.getTonnage());
            map.put("purchaseplant",updaInfo.getPurchaseplant());
            map.put("emissionstandard",updaInfo.getEmissionstandard());
            map.put("carshop",updaInfo.getCarshop());
            map.put("model",updaInfo.getModel());
            map.put("orderNumber",updaInfo.getOrderNumber());

            return new Response(0, "success", map);
        } catch (RRException ex) {
            return new Response(404, ex.getMessage(), null);
        }
    }
    @PostMapping("/vehicleinspect")  // 车检
    public Response vehicleinspect(@RequestParam int userId,
                                  @RequestParam String model,
                                   @RequestParam String purchaseplant,
                                   @RequestParam String picture,
                                   @RequestParam String emissionstandard) {

        try {

            UserRegistrationEntity updatedInfo = registratiService.vehicleinspect(userId,model,purchaseplant,picture, emissionstandard);
            return new Response(0, "success", updatedInfo);
        } catch (RRException ex) {
            return new Response(404, ex.getMessage(), null);
        }
    }


    @Autowired
    private UserService userService;

    @PostMapping("/updateDriversDatcher")  // 填写司机个人资料
    public Response updateDrivers(@RequestParam int userId,
                                  @RequestParam String name,
                                  @RequestParam String iphone,
                                  @RequestParam String id,
                                  @RequestParam int classification,
                                  @RequestParam String carNumber,
                                  @RequestParam int sex) {

        try {
            UserEntity updatedInfo = userService.updateUserInfo(userId, name, iphone, id, classification,carNumber, sex);
            UserWithCarNumber userWithCarNumber =new UserWithCarNumber(updatedInfo,updatedInfo.getCarnumber());
            return new Response(0, "success", userWithCarNumber);
        } catch (RRException e) {
            return new Response(404, e.getMessage(), null);
        }
    }
    @PostMapping("/updateDatcher")  // 填写助手个人资料
    public Response updateDatcher(@RequestParam int userId,
                                  @RequestParam String name,
                                  @RequestParam String iphone,
                                  @RequestParam String id,
                                  @RequestParam int classification,
                                  @RequestParam int sex) {

        try {
            UserEntity user = userService.updateDatcherr(userId, name, iphone, id, classification, sex);
            return new Response(0, "success", user);
        } catch (RRException e) {
            return new Response(404, e.getMessage(), null);
        }
    }
    @GetMapping("/datcherinfo") //返回助手用户信息
    public R datcher(@RequestParam int userId) {
        Map<String, Object> map = new HashMap<>();
        UserEntity datcher = userService.queryByuserID(userId);
        int driverid = datcher.getDriverId();
        if(driverid == 0){
            map.put("datcherinfo",datcher);
            map.put("drivername","未绑定司机");
            map.put("driveriphone","未绑定司机");
            return R.ok("未绑定司机").put("data", map);
        }
        UserEntity driver = userService.queryByuserID(datcher.getDriverId());
        datcher.setDrivernumber(driver.getCarnumber());
        userDao.updateById(datcher);
        map.put("datcherinfo", datcher);
        map.put("drivername", driver.getName());
        map.put("driveriphone", driver.getIPhone());
        return R.ok("success").put("data", map);
    }

    @PostMapping("/updatePictures")  //更改图片地址
    public Response updateUserPictures(@RequestBody UserPicUpdateVO userPicUpdate) {
        UserEntity updatedPic = userService.updateUserPic(userPicUpdate);
        return new Response(0, "success", updatedPic);
    }



    @PostMapping("/deleteOpenId")
    public R deleteOpenId(@RequestParam int userId) {
        UserEntity user = userDao.findByUserId(userId);
        if (user == null) {
            return R.error("用户不存在").put("data",null);
        }
        user.setOpenId("");
        user.setIPhone("");
        userDao.updateById(user);

        return R.ok("已解绑").put("data",user);
    }

}
